const fs = require("fs");
var shell = require("shelljs");
var { themeList, branchCheck, getShell, cuurentResolve } = require("./tool");
let errThemeNames = [];

function releaseMergeMaster(file) {
    console.log("------------------------------------------------执行" + file + " 合并");
    shell.cd(cuurentResolve(`/src/theme/${file}`));
    // 切换到master
    shell.exec(`git checkout master`);

    //拉去master
    if (getShell("git pull origin master", "----------------拉取master失败")) {
        if (branchCheck()) {
            shell.exec(`git checkout release`);
            shell.exec(`git pull origin release`);
            if(getShell("git merge master --allow-unrelated-histories", "----------------合并代码失败")){
                if(!getShell("git push origin release", "----------------推送失败")){
                    errThemeNames.push(file);
                }
            }else{
                errThemeNames.push(file);
            }
            shell.exec(`git checkout master`);
        }
    }else{
        errThemeNames.push(file);
    }
    shell.cd(cuurentResolve());
}

function releasePull() {
    const list = themeList();
    list.forEach((item) => {
        console.log("------------------------------------------------执行" + item + " release 拉取");
        shell.cd(cuurentResolve(`/src/theme/${item}`));
        shell.exec(`git checkout release`);
        if(!getShell("git pull origin release", "----------------拉取release失败")){
            errThemeNames.push(item);
        }
        shell.exec(`git checkout master`);
        shell.cd(cuurentResolve());
    });
    console.log("release pull 失败模版：", errThemeNames);

}

function releasePush() {
    const list = themeList();
    list.forEach((item) => {
        releaseMergeMaster(item);
    });
    console.log("release push 失败模版：", errThemeNames);

}
function release(name) {
    releaseMergeMaster(name);
}
module.exports = { releasePush, release,releasePull };
